/*
  Copyright (C) 2025 mio <stigma@disroot.org>

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "gemini_part.h"

#include <tqbuffer.h>
#include <tqregexp.h>

#include <tqtextbrowser.h>

#include <tdeaboutdata.h>
#include <tdeio/job.h>
#include <tdeparts/genericfactory.h>

using Factory = KParts::GenericFactory<GeminiPart>;
K_EXPORT_COMPONENT_FACTORY(libtdegemini_part, Factory);

#define DEBUG

#ifdef DEBUG
#include <iostream>
#define xinfo(...) do { std::cout << __FUNCTION__ << "(): " << __VA_ARGS__ << std::endl; } while (0)
#else
#define xinfo(...)
#endif

TDEAboutData* GeminiPart::createAboutData()
{
    auto about = new TDEAboutData("gemini_part", I18N_NOOP("gemini_part"), "1.0", I18N_NOOP("GemText Viewer"),
                                  TDEAboutData::License_GPL_V3, "(C) 2025 mio <stigma@disroot.org>");
    about->addAuthor("mio", I18N_NOOP("Creator / Maintainer"), "stigma@disroot.org", "https://yume-neru.neocities.org");
    return about;
}

GeminiPart::GeminiPart(TQWidget *parentWidget, const char *widgetName, TQObject *parent, const char *name, const TQStringList& args)
    : ReadOnlyPart(parent, widgetName)
    , m_buffer(nullptr)
{
    setInstance(Factory::instance());

    m_browser = new TQTextBrowser(parentWidget);
    setWidget(m_browser);
}


GeminiPart::~GeminiPart()
{
    delete m_buffer;
}

bool GeminiPart::openURL(const KURL& url)
{
    m_url = url;

    delete m_buffer;
    m_buffer = new TQBuffer();
    m_buffer->open(IO_ReadWrite);

    TDEIO::Job* job = TDEIO::get(url);

    connect(job, TQ_SIGNAL(result(TDEIO::Job*)), TQ_SLOT(slotResult(TDEIO::Job*)));
    connect(job, TQ_SIGNAL(data(TDEIO::Job*, const TQByteArray&)), TQ_SLOT(slotData(TDEIO::Job*, const TQByteArray&)));
        
    started(job);

    return true;
}

void GeminiPart::process()
{
    // TODO: Content may not be in UTF-8
    auto content = TQString::fromUtf8(m_buffer->readAll()).stripWhiteSpace();
    content.replace('<', "&lt;");
    TQStringList lines = TQStringList::split("\n", content);

    bool inBlockQuote = false;
    bool inPreformatted = false;
    bool inList = false;

    TQString html;
    TQRegExp linkRegExp("=>\\s+(\\S+)(\\s+.*$)?");
    for (const auto& line : lines) {
        if (line.startsWith("```")) {
            inPreformatted = !inPreformatted;

            if (inList) {
                html += "</ul>";
                inList = false;
            }

            if (inBlockQuote) {
                html += "</blockquote>";
                inBlockQuote = false;
            }

            if (inPreformatted) {
                html += "<pre>";
            } else {
                html += "</pre>";
            }
            continue;
        }

        if (inPreformatted) {
            html += TQString("%1\n").arg(line);
            continue;
        }

        if (line.startsWith("*")) {
            if (!inList) {
                html += "<ul>";
                inList = true;
            }
            html += TQString("<li>%1</li>").arg(line.mid(1).stripWhiteSpace());
            continue;
        }

        if (inList) {
            inList = false;
            html += "</ul>";
        }

        if (line.startsWith(">")) {
            if (!inBlockQuote) {
                html += "<blockquote>";
                inBlockQuote = true;
            }

            // NOTE: As Gemini is line-oriented, this will "hard-wrap" each line.
            html += TQString("%1<br>").arg(line.mid(1).stripWhiteSpace());
            continue;
        }

        if (inBlockQuote) {
            inBlockQuote = false;
            html += "</blockquote>";
        }

        if (line.startsWith("###")) {
            html += TQString("<h3>%1</h3>").arg(line.mid(3).stripWhiteSpace());
            continue;
        }
        if (line.startsWith("##")) {
            html += TQString("<h2>%1</h2>").arg(line.mid(2).stripWhiteSpace());
            continue;
        }
        if (line.startsWith("#")) {
            html += TQString("<h1>%1</h1>").arg(line.mid(1).stripWhiteSpace());
            continue;
        }

        if (line.startsWith("=>")) {
            int found = linkRegExp.search(line);
            if (found == -1) {
                /* Invalid */
                continue;
            }
            int num = linkRegExp.numCaptures();

            KURL url(linkRegExp.cap(1));
            if (!url.isValid()) {
                // Relative URL
                url = KURL(m_url, linkRegExp.cap(1));
            }
                    
            html += TQString("<p><a href=\"%1\">%2</a></p>").arg(url.url()).arg(num > 1 ? linkRegExp.cap(2) : url.prettyURL());
            continue;
        }

        html += "<p>" + line + "</p>";
    }

    m_browser->setText(html);
    completed();
}

void GeminiPart::slotData(TDEIO::Job* job, const TQByteArray& data)
{
    if (data.size() == 0)
        return;
    m_buffer->writeBlock(data.data(), data.size());
}

void GeminiPart::slotResult(TDEIO::Job* job)
{
    if (job->error() != 0) {
        canceled(job->errorString());
        job->showErrorDialog(widget());
        return;
    }

    m_buffer->reset();
    process();
}

#include "gemini_part.moc"
